package com.cn.onetrip.rorate3d;

import android.app.Activity;
import android.content.Context;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Transformation;
import android.widget.Gallery;

import com.cn.onetrip.activity.ScenicAtlasActivity;

public class AtlasGallery extends Gallery {

	private Camera mCamera = new Camera();
	private int mMaxRotationAngle = 20;
	private int mMaxZoom = -160;
	private int mCoveflowCenter;

	private GestureDetector gestureScanner;
	private ScaleImageView imageView;
	private Context mContext;

	private int screenHeight, screenWidth;

	public AtlasGallery(Context context) {
		super(context);
		mContext = context;
		setScreenSize();
		touchScale();
	}

	public AtlasGallery(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mContext = context;
		setScreenSize();
		touchScale();
	}

	public AtlasGallery(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		setScreenSize();
		touchScale();
	}

	private void touchScale() {
		gestureScanner = new GestureDetector(new MySimpleGesture());
		this.setOnTouchListener(new OnTouchListener() {
			// set the ImageView scale
			float baseValue;
			float originalScale;

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				View view = AtlasGallery.this.getSelectedView();
				if (view instanceof ScaleImageView) {
					imageView = (ScaleImageView) view;
					if (event.getAction() == MotionEvent.ACTION_DOWN) {
						baseValue = 0;
						originalScale = imageView.getScale();
					}
					if (event.getAction() == MotionEvent.ACTION_MOVE) {
						if (event.getPointerCount() == 2) {
							float x = event.getX(0) - event.getX(1);
							float y = event.getY(0) - event.getY(1);
							float value = (float) Math.sqrt(x * x + y * y);
							if (baseValue == 0) {
								baseValue = value;
							} else {
								float scale = value / baseValue;
								// scale the image
								imageView.zoomTo(originalScale * scale, x
										+ event.getX(1), y + event.getY(1));
							}
						}
					}
				}
				return false;
			}

		});
	}

	public void setScreenSize() {
		DisplayMetrics dm = new DisplayMetrics();
		((Activity) mContext).getWindowManager().getDefaultDisplay()
				.getMetrics(dm);

		screenHeight = dm.heightPixels;
		screenWidth = dm.widthPixels;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		View view = AtlasGallery.this.getSelectedView();
		System.out.print("onScroll");
		if (view instanceof ScaleImageView) {
			imageView = (ScaleImageView) view;
			float v[] = new float[9];
			Matrix m = imageView.getImageMatrix();
			m.getValues(v);
			float left, right;
			float width, height;
			width = imageView.getScale() * imageView.getImageWidth();
			height = imageView.getScale() * imageView.getImageHeight();
			if ((int) width <= screenWidth && (int) height <= screenHeight) {
				System.out.println();
				return super.onScroll(e1, e2, distanceX * 2.0f, distanceY);
			} else {
				left = v[Matrix.MTRANS_X];
				right = left + width;
				Rect r = new Rect();
				imageView.getGlobalVisibleRect(r);

				if (distanceX > 0) {
					if (r.left > 0) {
						super.onScroll(e1, e2, distanceX * 2.0f, distanceY);
					} else if (right <= screenWidth) {
						super.onScroll(e1, e2, distanceX * 2.0f, distanceY);
					} else {
						imageView.postTranslate(-distanceX * 2.0f, -distanceY);
					}
				} else if (distanceX < 0) {
					if (r.right < screenWidth) {
						super.onScroll(e1, e2, distanceX * 2.0f, distanceY);
					} else if (left >= 0) {
						super.onScroll(e1, e2, distanceX * 2.0f, distanceY);
					} else {
						imageView.postTranslate(-distanceX * 2.0f, -distanceY);
					}
				}
			}

		} else {
			super.onScroll(e1, e2, distanceX * 2.0f, distanceY);
		}
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		return false;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		gestureScanner.onTouchEvent(event);
		switch (event.getAction()) {
		case MotionEvent.ACTION_UP:
			View view = AtlasGallery.this.getSelectedView();
			if (view instanceof ScaleImageView) {
				imageView = (ScaleImageView) view;
				float width = imageView.getScale() * imageView.getImageWidth();
				float height = imageView.getScale()
						* imageView.getImageHeight();
				if ((int) width <= screenWidth && (int) height <= screenHeight) {
					break;
				}
				float v[] = new float[9];
				Matrix m = imageView.getImageMatrix();
				m.getValues(v);
				float top = v[Matrix.MTRANS_Y];
				float bottom = top + height;
				if (top > 0) {
					imageView.postTranslateDur(-top, 200f);
				}
				Log.i("manga", "bottom:" + bottom);
				if (bottom < screenHeight) {
					imageView.postTranslateDur(screenHeight - bottom, 200f);
				}

			}
			break;
		}
		return super.onTouchEvent(event);
	}

	public int getmMaxRotationAngle() {
		return mMaxRotationAngle;
	}

	public void setmMaxRotationAngle(int mMaxRotationAngle) {
		this.mMaxRotationAngle = mMaxRotationAngle;
	}

	public int getmMaxZoom() {
		return mMaxZoom;
	}

	public void setmMaxZoom(int mMaxZoom) {
		this.mMaxZoom = mMaxZoom;
	}

	private int getCenterOfCoverflow() {
		return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2
				+ getPaddingLeft();
	}

	private static int getCenterOfView(View view) {
		return view.getLeft() + view.getWidth() / 2;
	}

	@Override
	protected boolean getChildStaticTransformation(View child, Transformation t) {
		final int childCenter = getCenterOfView(child);
		final int childWidth = child.getWidth();
		int rotationAngle = 0;

		t.clear();
		t.setTransformationType(Transformation.TYPE_MATRIX);

		if (childCenter == mCoveflowCenter) {
			transformImageBitmap((View) child, t, 0);
		} else {
			rotationAngle = (int) (((float) (mCoveflowCenter - childCenter) / childWidth) * mMaxRotationAngle);
			if (Math.abs(rotationAngle) > mMaxRotationAngle) {
				rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle
						: mMaxRotationAngle;
			}
			transformImageBitmap((View) child, t, rotationAngle);
		}

		return true;
	}

	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		mCoveflowCenter = getCenterOfCoverflow();
		super.onSizeChanged(w, h, oldw, oldh);
	}

	private void transformImageBitmap(View child, Transformation t,
			int rotationAngle) {
		mCamera.save();
		final Matrix imageMatrix = t.getMatrix();
		final int imageHeight = child.getLayoutParams().height;
		final int imageWidth = child.getLayoutParams().width;
		final int rotation = Math.abs(rotationAngle);

		mCamera.translate(0.0f, 0.0f, -rotation);
		// As the angle of the view gets less, zoom in
		if (rotation < mMaxRotationAngle) {
			float zoomAmount = (float) (mMaxZoom + (rotation * 1.5));
			mCamera.translate(0.0f, 0.0f, -rotation);
		}

		mCamera.rotateX(rotationAngle / 4.0f);
		mCamera.rotateY(rotationAngle * 1.5f);
		mCamera.rotateZ(rotationAngle);

		mCamera.getMatrix(imageMatrix);

		imageMatrix.preTranslate(-(screenWidth / 2), -(screenHeight / 2));
		imageMatrix.postTranslate((screenWidth / 2), (screenHeight / 2));

		// imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));
		// imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));

		mCamera.restore();
	}

	private class MySimpleGesture extends SimpleOnGestureListener {

		public boolean onDoubleTap(MotionEvent e) {
			View view = AtlasGallery.this.getSelectedView();
			if (view instanceof ScaleImageView) {
				imageView = (ScaleImageView) view;
				if (imageView.getScale() > imageView.getScaleRate()) {
					imageView.zoomTo(imageView.getScaleRate(), screenWidth / 2,
							screenHeight / 2, 200f);
					// imageView.layoutToCenter();
				} else {
					imageView.zoomTo(1.0f, screenWidth / 2, screenHeight / 2,
							200f);
				}
			}
			return true;
		}

		@Override
		public boolean onSingleTapUp(MotionEvent e) {
			ScenicAtlasActivity parentActivity = (ScenicAtlasActivity) mContext;
			parentActivity.setTextViewState();
			return super.onSingleTapUp(e);
		}
	}
}
